//
//  SYSpecialViewController.m
//  Term Of Section B
//
//  Created by 韩震明 on 15/11/27.
//  Copyright © 2015年 韩震明. All rights reserved.
//

#import "SYSpecialViewController.h"

@interface SYSpecialViewController ()<UITableViewDataSource,
                                      UITableViewDelegate,
                                      UICollectionViewDataSource,
                                      UICollectionViewDelegate,
                                      SDCycleScrollViewDelegate,
                                      UIGestureRecognizerDelegate>

@property (nonatomic, strong) SYBaseTableView *tableView;
// scroll三方
@property (nonatomic, strong) SDCycleScrollView *scroll;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) SYBaseCollectionView *collection;
/*! scrollView数据 */
@property (nonatomic, strong) NSMutableArray *banner;
/*! collectionView数据 */
@property (nonatomic, strong) NSMutableArray *entry_list;
/*! tableView数据 */
@property (nonatomic, strong) NSMutableArray *topic;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UIView *backOfSCView;

@end

@implementation SYSpecialViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 顶部状态栏样式
    [UIApplication sharedApplication].statusBarStyle
    = UIStatusBarStyleLightContent;
    // 设置顶部状态栏
    UIView *status = [[UIView alloc] init];
    [self.navigationController.view addSubview:status];
    status.backgroundColor = [UIColor redColor];
    [self setNeedsStatusBarAppearanceUpdate];
    [status makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.and.right.equalTo(self.navigationController.view);
        HEIGHTToNum(20);
    }];
}



- (BOOL)prefersStatusBarHidden
{
    // 顶部状态栏是否隐藏
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.hidesBarsOnSwipe = YES;
    [self createTableView];
    
    [self createScrollView];
    
    [self createCollectionView];
    
    // 小菊花
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"正在加载...";
    
    [self createSVCData];
    
    [self refresh];
    
    [self showStatus];
}

#pragma - mark NetWork Status

- (void)showStatus
{
    // 判断网络状态并提示
    [AFN showNetWorkStatus:^(NSString *status) {
        if (![status isEqualToString:@"wifi已连接"] ||
            [status isEqualToString:@"网络已连接"]) {
            [ENAlert alertShowTitle:@"当前网络状态"
                            message:status
                  cancelButtonTitle:@"确定"
                  otherButtonTitles:nil
                              block:nil];
        }
    }];
}

#pragma mark - MJRefresh Method

- (void)refresh
{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 0;
        [self createSVCData];
    }];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        [self createSVCData];
    }];
}

#pragma mark - ScrollView

- (void)createScrollView
{
    self.scroll = [[SDCycleScrollView alloc] init];
    [self.backOfSCView addSubview:self.scroll];
    self.scroll.placeholderImage = [UIImage imageNamed:@"navigationBarImage"];
    self.scroll.delegate = self;
    self.scroll.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    self.scroll.dotColor = [UIColor colorWithRed:0.6124 green:0.9486 blue:0.9881 alpha:1.0];
    [self.scroll makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.and.right.equalTo(self.backOfSCView);
        HEIGHTToNum(200);
    }];
}
                   
- (void)reloadPicArr
{
    NSMutableArray *picArr = [NSMutableArray array];
    for (NSInteger i = 0; i < self.banner.count; i++) {
        [picArr addObject:[self.banner[i] photo]];
    }
    // 加入网络图片数组
    self.scroll.imageURLStringsGroup = picArr;
}

#pragma mark - ScrollView Delegate Method

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    // 判断类型
    if ([[self.banner[index] bannerType] isEqualToString:@"topic_list"]) {
        SYScrollDetailsViewController *bannerDetailsVC = [[SYScrollDetailsViewController alloc] init];
        bannerDetailsVC.bannerModel = self.banner[index];
        bannerDetailsVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:bannerDetailsVC animated:YES];
    } else {
        SYBaseWebView *webView = [[SYBaseWebView alloc] init];
        webView.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:webView animated:YES];
        webView.WebViewUrlStr = [self.banner[index] extend];
        webView.titleForWeb = [self.banner[index] title];
    }
    
}

#pragma mark - TableView Setting

- (void)createTableView
{
    // 头部创建
    self.backOfSCView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 320)];
    // 自定义的tableView初始化方法
    self.tableView = [[SYBaseTableView alloc] initWithFrame:self.view.frame
                                                      style:UITableViewStylePlain
                                                  superView:self.view
                                                   delegate:self
                                                  rowHeight:150
                                             separatorStyle:NO
                               showsVerticalScrollIndicator:NO
                             showsHorizontalScrollIndicator:NO
                                                     header:self.backOfSCView];
    
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.and.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(- 55);
    }];
    
    self.tableView.backgroundColor = [UIColor clearColor];
    // 注册cell
    [self.tableView registerClass:[SYSpecialTVCell class] forCellReuseIdentifier:@"tableView"];
    
//    self.tableView.arrCount = self.topic.count;
}

#pragma mark - TableView Delegate Method

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topic.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SYSpecialTVCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"tableView"];
    cell.topicModel = self.topic[indexPath.row];
    return cell;
}

#pragma mark Cell Did Selected

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.topic[indexPath.row] cellType] isEqualToString:@"0"]) {
        SYTableViewDetailsVC *tableVC = [[SYTableViewDetailsVC alloc] init];
        tableVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:tableVC animated:YES];
        tableVC.urlStr = [NSString stringWithFormat:@"http://open3.bantangapp.com/topic/info?app_installtime=1445332782.662591&app_versions=4.2.3&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&id=%@&oauth_token=bf8be334eb1fd06b1bf65f5883dd415a&os_versions=9.1&screensize=1242&statistics_uv=1&track_device_info=iPhone72C1&track_deviceid=2F83AC09-B470-4C43-9DEE-E0FB95B4B438&track_user_id=1457891&v=7", [self.topic[indexPath.row] cellId]];
        tableVC.topicModel = self.topic[indexPath.row];
    } else {
        SYTableDetaislType1VC *type = [[SYTableDetaislType1VC alloc] init];
        type.strUrl = [NSString stringWithFormat:@"http://open3.bantangapp.com/topic/info?app_installtime=1445332782.662591&app_versions=4.2.3&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&id=%@&oauth_token=bf8be334eb1fd06b1bf65f5883dd415a&os_versions=9.1&screensize=1242&statistics_uv=1&track_device_info=iPhone72C1&track_deviceid=2F83AC09-B470-4C43-9DEE-E0FB95B4B438&track_user_id=1457891&v=7", [self.topic[indexPath.row] cellId]];
        type.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:type animated:YES];
    }
}

#pragma mark - CollectionView Setting

- (void)createCollectionView
{
    SYBaseCollectionViewFlowLayout *flowLayout = [[SYBaseCollectionViewFlowLayout alloc] initWithItemSize:CGSizeMake(100, 100) scrollDirection:UICollectionViewScrollDirectionHorizontal sectionInsert:UIEdgeInsetsMake(1, 3, 1, 3)];
    
    self.collection = [[SYBaseCollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout backgroundColor:[UIColor whiteColor] superView:self.backOfSCView showsHorizontalScrollIndicator:NO showsVerticalScrollIndicator:NO delegate:self];
    
    [self.collection makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.and.right.equalTo(self.backOfSCView);
        HEIGHTToNum(120);
    }];
    
    [self.collection registerClass:[SYSpecialCVCell class] forCellWithReuseIdentifier:@"collectionReuse"];
}

#pragma mark - CollectionView Delegate Method

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.entry_list.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SYSpecialCVCell *cell = [self.collection dequeueReusableCellWithReuseIdentifier:@"collectionReuse" forIndexPath:indexPath];
    cell.entry_list = self.entry_list[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        SYCollectionDetailsVC *sdVC = [[SYCollectionDetailsVC alloc] init];
        sdVC.hidesBottomBarWhenPushed = YES;
        sdVC.listModel = self.entry_list[indexPath.row];
        [self.navigationController pushViewController:sdVC animated:YES];
    } else {
        SYOthersDetailsViewController *otVC = [[SYOthersDetailsViewController alloc] init];
        otVC.hidesBottomBarWhenPushed = YES;
        otVC.typeId = [self.entry_list[indexPath.row] collectionId];
        [self.navigationController pushViewController:otVC animated:YES];
    }
}

#pragma mark - CreateSVCData

- (void)createSVCData
{
    NSString *strUrl = [NSString stringWithFormat:@"http://open3.bantangapp.com/recommend/index?app_installtime=1445332782.662591&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=bf8be334eb1fd06b1bf65f5883dd415a&os_versions=9.0.2&page=%ld&pagesize=20&screensize=1242&track_device_info=iPhone7%dC1&track_deviceid=2F83AC09-B470-4C43-9DEE-E0FB95B4B438&track_user_id=1457891&v=7", self.page, 2];
    [AFN GETDataWithURL:strUrl block:^(id result) {
        if (self.page == 0) {
            NSMutableDictionary *dic = result;
            self.banner = [NSMutableArray array];
            self.banner = [SYSpecialScrollModel baseModelByArr:dic[@"data"][@"banner"]];
            
            self.entry_list = [NSMutableArray array];
            self.entry_list = [SYSpecialCollectionModel baseModelByArr:dic[@"data"][@"entry_list"]];
            
            self.topic = [NSMutableArray array];
            self.topic = [SYSpecialTableViewModel baseModelByArr:dic[@"data"][@"topic"]];
            
            if (self.topic.count > 0) {
                [self.tableView reloadData];
                [self reloadPicArr];
                [self.collection reloadData];
                [self.hud removeFromSuperview];
                [self.tableView.header endRefreshing];
            } else {
                NSLog(@"数据加载失败");
            }
        } else {
            NSMutableDictionary *dic = result;
            NSMutableArray *arr = [NSMutableArray array];
            arr = [SYSpecialTableViewModel baseModelByArr:dic[@"data"][@"topic"]];
            [self.topic addObjectsFromArray:arr];
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
            if (self.page >= 21) {
                [self.tableView.footer endRefreshingWithNoMoreData];
            }
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
